package com.fs.iot.service;

import com.fs.common.exception.AppException;
import com.fs.iot.bean.dto.DeviceDTO;
import com.fs.iot.bean.dto.DeviceSimulationDTO;
import com.fs.common.ErrorCodes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 设备服务
 *
 * @author LiuQi 2025/3/23-20:24
 * @version V1.0
 **/
@Service
public class DeviceService {
    @Autowired
    private DeviceSimulationService deviceSimulationService;

    @Autowired
    private DeviceSimulationEntityService simulationEntityService;

    @Autowired
    private DeviceEntityService deviceEntityService;

    @Autowired
    private KafkaNoticeService kafkaNoticeService;

    /**
     * 启动设备模拟程序
     * @param deviceCode 设备编号
     */
    public void start(String deviceCode) {
        DeviceSimulationDTO deviceDTO = simulationEntityService.findByCode(deviceCode).orElseThrow(AppException.supplier(ErrorCodes.IOT_DEVICE_NOT_EXISTS));
        deviceSimulationService.restartSimulation(deviceDTO);
        deviceDTO.setStatus(1);
        simulationEntityService.update(deviceDTO);
    }

    /**
     * 停止设备模拟程序
     * @param deviceCode 设备编号
     */
    public void stop(String deviceCode) {
        DeviceSimulationDTO deviceDTO = simulationEntityService.findByCode(deviceCode).orElseThrow(AppException.supplier(ErrorCodes.IOT_DEVICE_NOT_EXISTS));
        deviceSimulationService.stopSimulation(deviceCode);
        deviceDTO.setStatus(0);
        simulationEntityService.update(deviceDTO);
    }

    public DeviceDTO insert(DeviceDTO req) {
        req = deviceEntityService.insert(req);
        kafkaNoticeService.sendDeviceNotice(req);
        return req;
    }

    public void update(DeviceDTO req) {
        deviceEntityService.update(req);
        deviceEntityService.findById(req.getId())
                .ifPresent(kafkaNoticeService::sendDeviceNotice);
    }

    public void delete(String id) {
        deviceEntityService.delete(id);
    }

    public void offline(String id) {
        deviceEntityService.offline(id);
    }

    public void publish(String id) {
        deviceEntityService.publish(id);
        deviceEntityService.findById(id)
                .ifPresent(kafkaNoticeService::sendDeviceNotice);
    }
}
